package cn.liuawen;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

/**
 * @author : Liu Awen Email:willowawen@gmail.com
 * @create : 2020-06-10
 * Set 写 Map
 */
public class EcutSet<E> implements Set<E> {

    private transient HashMap<E, Object> map;
    private static final Object PRESENT = new Object();

    public EcutSet() {
        map = new HashMap<>();
    }

    @Override
    public int size() {
        return map.size();
    }

    @Override
    public boolean isEmpty() {
        return map.isEmpty();
    }

    @Override
    public boolean contains(Object o) {
        return map.containsKey(o);
    }

    @Override
    public Iterator<E> iterator() {
        return map.keySet().iterator();
    }

    @Override
    public <T> T[] toArray(T[] a) {
        return null;
    }

    @Override
    public boolean add(E e) {
        return map.put(e, PRESENT) == null;
    }

    @Override
    public boolean remove(Object o) {
        return map.remove(o) == PRESENT;
    }

    @Override
    public boolean containsAll(Collection<?> c) {
        Iterator<?> it = c.iterator();
        while(it.hasNext()) {
            if(!contains(it.next())) {
                return false;
            }
        }
        return true;
    }

    @Override
    public boolean addAll(Collection<? extends E> c) {
        boolean t = false;
        Iterator<E> it =  (Iterator<E>) c.iterator();
        while(it.hasNext()) {
            if(add(it.next())) {
                t = true;
            }
        }
        return t;
    }


    @Override
    public Object[] toArray() {
        Object[] s = new Object[size()];
        int i = 0;
        Iterator<E> it = iterator();
        while(it.hasNext()) {
            s[i++] = it.next();
        }
        return s;
    }

    @Override
    public boolean retainAll(Collection<?> c) {
        boolean t = false ;
        Iterator<E> it = iterator();
        while(it.hasNext()) {
            Object o = it.next();
            if(!c.contains(o)) {
                it.remove();
                t = true;
            }
        }

        return t;
    }

    @Override
    public boolean removeAll(Collection<?> c) {
        boolean t = false;
        Iterator<?> it = c.iterator();
        while(it.hasNext()) {
            Object o = it.next();
            if(contains(o)) {
                remove(o);
                t = true;
            }
        }
        return t;
    }

    @Override
    public void clear() {
        map.clear();

    }

    @Override
    public String toString() {
        Iterator<E> it = iterator();
        StringBuilder s = new StringBuilder("[");
        while(it.hasNext()) {
            s.append(it.next().toString());
            s.append(it.hasNext() ? "," : "");
        }
        s.append("]");
        return s.toString();
    }

}